package com.ciei.dpagm.util;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class StringUtil {

	/**
	 * 正整数正则表达式
	 */
	private static final Pattern POSITIVE_INTEGER_PATTERN = Pattern.compile("^[1-9]\\d*$");

	public static boolean isNullOrEmpty(String str){
		if(str==null){
			return true;
		}else{
			if(str.trim().length()==0){
				return true;
			}
		}
		return false;
	}

	public static String nullToEmpty(String str){
		if(str == null){
			return StringUtils.EMPTY;
		}
		return str;
	}
	
	public static Integer nullToMax(Integer num){
		if(num == null){
			return Integer.MAX_VALUE;
		}
		return num;
	}
	
	public static String lowerFirstChar(String s) {
		return s.substring(0,1).toLowerCase() + (s.length()>1?s.substring(1):"");
	}
	
	public static String UpperFirstChar(String s) {
		return s.substring(0,1).toUpperCase() + (s.length()>1?s.substring(1):"");
	}
	
	/**
	 * 把xml 转为object
	 * 
	 * @param xml
	 * @return
	 */
	public static Object xmlToObject(String xml) {
		try {
			ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes("UTF8"));
			XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in));
			return decoder.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String toString(Object o){
		if(o==null) {
			return "";
		}
		else{
			return  o.toString();
		}

	}

	/**
	 * 判断字符串是否为正整数
	 * @param str
	 * @return
	 */
	public static boolean isPositiveInteger(String str) {
		return str != null && POSITIVE_INTEGER_PATTERN.matcher(str).matches();
	}


	/**
	 * 如果字符串isNullOrEmpty，则返回空"";
	 * @param str
	 * @return
	 */
	public static String getString(String str){
		if (StringUtil.isNullOrEmpty(str)){
			return "";
		}
		return str;
	}

	/**
	 * 判断给定字符串是否为数字
	 * @param str
	 * @return
	 */
	public static Boolean isNumeric(String str) {
		return str.matches("-?[0-9]+.?[0-9]*");
	}
}
